package com.itheima.d4_algorithm;

import java.util.Random;

public class demo4 {
    static Long m = 1L;
    // 交换数组中两个元素的位置
    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // 判断数组是否已经有序
    public static boolean isSorted(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                return false;
            }
        }
        return true;
    }

    // 猴子排序（随机排序）的核心方法
    public static void monkeySort(int[] arr) {

        Random random = new Random();
        while (!isSorted(arr)) {
            // 随机打乱数组元素顺序
            for (int i = 0; i < arr.length; i++) {
                System.out.println(m++);
                int randomIndex = random.nextInt(arr.length);
                swap(arr, i, randomIndex);
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {145,7,89,34,2,98,453,12,82,126,324,199};

        monkeySort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
